//
//  HMEmotionCell.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMEmotionCell: UICollectionViewCell {
    
    lazy var emoticonButtons = [HMEmoticonButton]()
    
    /// 外界设置进来的表情数组
    var emoticons: [HMEmoticon]? {
        didSet {
            print(emoticons)
            
            // 先让所有的表情按钮隐藏
            for button in emoticonButtons {
                button.isHidden = true
            }
            
            for (index, emoticon) in emoticons!.enumerated() {
                
                // 取到对应位置的按钮
                let button = emoticonButtons[index]
                // 要设置数据的话就让按钮显示
                button.isHidden = false
                // 给按钮设置一个表情模型
                button.emoticon = emoticon
            }
        }
    }

    
    /// 提供给外界设置的indexPath属性
    var indexPath: IndexPath? {
        didSet {
            label.text = "第\(indexPath!.section)组，第\(indexPath!.item)页"
            // 根据indexPath的section去显示或者隐藏recentLabel
            recentLabel.isHidden = indexPath!.section != 0
        }
    }

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        contentView.addSubview(label)
        
        label.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView)
        }
        
        // 添加20个按钮
        addChildButtons()
        contentView.addSubview(deleteButton)
        contentView.addSubview(recentLabel)
        
        recentLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView.snp_bottom).offset(-10)
        }
        
        // 添加长按手势
        let ges = UILongPressGestureRecognizer(target: self, action: #selector(longPress(ges:)))
        addGestureRecognizer(ges)
    }
    
    
    
    /// 表情按钮点击
    ///
    /// - parameter button: <#button description#>
    @objc private func emoticonButtonClick(button: HMEmoticonButton) {
        print(button.emoticon?.chs)
        
        // 1. 取到模型
        let emoticon = button.emoticon
        
        // 2. 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: HMEmoticonButtonDidSelectedNotification), object: nil, userInfo: ["emoticon": emoticon!])
        
        // 下面的代码是显示paopao
        
        // 初始化
        let paopaoView = HMEmoticonPaopaoView.paopaoView()
        // 设置数据
        paopaoView.emoticonButton.emoticon = button.emoticon
        
        // 4. 调整paopaoView的位置
        let window = UIApplication.shared.windows.last!
        
        // 将按钮的rect转换到window上
        let rect = button.convert(button.bounds, to: window)
        
        // 设置中心x
        paopaoView.center.x = rect.midX
        // 设置y值
        paopaoView.frame.origin.y = rect.maxY - paopaoView.frame.height
        
        window.addSubview(paopaoView)
        
        //
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            paopaoView.removeFromSuperview()
        }
        
        
    }

    
    /// 长按手势触发的方法
    ///
    /// - parameter ges: <#ges description#>
    @objc private func longPress(ges: UILongPressGestureRecognizer) {
        print(ges.location(in: self))
        
        func getButton(location: CGPoint) -> HMEmoticonButton? {
            // 遍历表情按钮
            for button in emoticonButtons {
                if button.frame.contains(location) {
                    return button
                }
            }
            return nil
        }
        
        switch ges.state {
        case .began,.changed:
            // 1. 取到手指的位置
            let location = ges.location(in: self)
            
            // 2. 判断手指的位置是处于哪个按钮之上的
            if let button = getButton(location: location) {
                // 3. 取到该按钮的表情模型，并且让paopao显示数据
                let emoticon = button.emoticon
                // 初始化paopaoView
                paopaoView.emoticonButton.emoticon = emoticon
                // 4. 调整paopaoView的位置
                let window = UIApplication.shared.windows.last!
                
                // 将按钮的rect转换到window上
                let rect = button.convert(button.bounds, to: window)
                
                // 设置中心x
                paopaoView.center.x = rect.midX
                // 设置y值
                paopaoView.frame.origin.y = rect.maxY - paopaoView.frame.height
                
                window.addSubview(paopaoView)
            }else{
                paopaoView.removeFromSuperview()
            }
        case .ended, .cancelled, .failed:
            paopaoView.removeFromSuperview()
        default:
            break
        }
        
    }

    
    private func addChildButtons() {
        for _ in 0..<HMEmoticonKeyboardPageEmoticonCount {
            let button = HMEmoticonButton()
            
            button.addTarget(self, action: #selector(emoticonButtonClick(button:)), for: UIControlEvents.touchUpInside)

            button.titleLabel?.font = UIFont.systemFont(ofSize: 34)
//            button.backgroundColor = RandomColor
            contentView.addSubview(button)
            // 保存一份到数组
            emoticonButtons.append(button)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 每一个表情按钮的宽度与高度
        let itemW = self.bounds.width / 7
        let itemH = (self.bounds.height - 20) / 3
        
        // 如何在这个地方取到所有的表情按钮呢？
        
        for (index, button) in emoticonButtons.enumerated() {
            // 1. 取到按钮的列数
            let col = index % 7
            // 2. 取到按钮的行数
            let row = index / 7
            // 3. 确定按钮的x值
            let x = CGFloat(col) * itemW
            // 4. 确定的按钮y值
            let y = CGFloat(row) * itemH
            // 5. 设置按钮的frame
            button.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
        }
        
        deleteButton.frame = CGRect(x: self.bounds.width - itemW, y: itemH * 2, width: itemW, height: itemH)
        
    }


    
    // MARK: - 懒加载控件
    
    private lazy var label: UILabel = {
        let label = UILabel(textColor: UIColor.black, fontSize: 35)
        return label
    }()
    
    private lazy var recentLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGray, fontSize: 12)
        label.text = "最近使用的表情"
        return label
    }()

    
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), for: .highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), for: .normal)
        
        return button
    }()
    
    private lazy var paopaoView: HMEmoticonPaopaoView = HMEmoticonPaopaoView.paopaoView()

    
}
